//
// Created by wujehy on 2020/7/8.
//

#include "MySQLCpp/DataBase.h"
#include "MySQLCpp/Exception.h"
#include <mysql/mysql.h>
#include <iostream>

using namespace GeeJoan::MySQL;

DataBase::DataBase(
        const std::string &mHost, unsigned int mPort, const std::string &mDatabase, const std::string &mUsername,
        const std::string &mPassword) : m_host( mHost ), m_port( mPort ), m_database( mDatabase ),
                                        m_username( mUsername ), m_password( mPassword )
{
    m_db_hander = new MYSQL;
    mysql_init( m_db_hander );

    if (!mysql_real_connect( m_db_hander, mHost.c_str(), mUsername.c_str(), mPassword.c_str(), mDatabase.c_str(),
                             m_port, NULL, 0 ))
    {
        throw Exception( m_db_hander );
    }
}


//DataBase::DataBase(const std::string &mHost , const std::string &mDatabase, const std::string &mUsername,
//                   const std::string &mPassword) :  {
//    m_db_hander = new MYSQL;
//    mysql_init(m_db_hander);
//
//    if(!mysql_real_connect(m_db_hander,mHost.c_str(),mUsername.c_str(),mPassword.c_str() ,mDatabase.c_str(),m_port,NULL,0))
//    {
//        throw Exception(m_db_hander);
//    }
//}

DataBase::~DataBase()
{
    if (m_db_hander)
    {
        mysql_close( m_db_hander );
        delete m_db_hander;
    }
    mysql_library_end();
}

int DataBase::exec(const char *sql)
{
    check( 0 );

    int ret = mysql_query( m_db_hander, sql );

    if (ret)
    {
        throw Exception( m_db_hander );
    }
    int change = mysql_affected_rows( getHander());
    return change;
}

MYSQL *DataBase::getHander()
{
    return m_db_hander;
}

int DataBase::changeDB(const char *dbName)
{
    check( 0 );

    int ret = mysql_select_db( m_db_hander, dbName );
    if (ret)
    {
        throw Exception( m_db_hander );
    }
    return 0;
}

